<template>
    <div class="app-content">
        <el-form :model="formInline" :rules="rules" ref="formInline" label-width="140px"  label-position="right" slot="form" >   
            <div class="box">
                <div class="appTitle"><h3>成绩发布</h3></div>

                <!-- <el-row :gutter="21">
                    <el-col :span="12">
                        <el-form-item label="选择学校"  prop="schoolName">
                            <el-select  :disabled="true" v-model="getSchool" filterable remote clearable reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="schoolLoading"  style="width:95%;" @change="queryAllClass(getSchool)">
                                <el-option v-for="item in formInline.schoolNameList" :key="item.schoolId" :label="item.schoolName" :value="item.schoolId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row> -->

                <el-row :gutter="21">
                    <el-col :span="12">
                        <el-form-item label="选择班级" prop="typeClass">
                                <el-select v-model="formInline.typeClass" @change = "queryClassType" style="width:95%;">
                                <el-option v-for="item in formInline.classList" :key="item.pId" :label="item.sNickName" :value="item.pId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="21">
                    <el-col :span="12">
                        <el-form-item label="考试类型" prop="typeExam">
                                <el-select v-model="formInline.typeExam" style="width:95%;">
                                <el-option v-for="item in formInline.examType" :key="item.examTypeId" :label="item.examTypeName" :value="item.examTypeId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="21">

                     <el-col :span="12">
                        <el-form-item label="本次考试开始日期" prop="startDate">
                            <el-date-picker :editable="false"  v-model="formInline.startDate" style="width:95%;" type="date" format="yyyy-MM-dd" placeholder="请选择日期" :picker-options="formInline.pickerOptions">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    
                </el-row> 
                <el-row :gutter="21">
                    <el-col :span="18" style="min-height:80px">
                        
                        <el-form-item label="选择科目"  class="subjectKuang" prop="subjectIds" v-if = "showSub">
                            
                            <el-checkbox-group v-model="subChecked" style = "margin-left: -8px">
                                <template v-for="(item,index) in dynamicTags">
                                    <el-checkbox class = "sub" :key="index" :label="item.name"></el-checkbox>
                                </template>
                            </el-checkbox-group>
                        
                        </el-form-item>

                    </el-col>
                </el-row>
                
                 <!-- prop="selectFiles" -->
                <el-form-item label="添加附件" prop="selectFiles">

                    <!-- :gutter="21" -->
                    <el-row>

                        <el-col :span="12">
                            <el-form-item label="" prop="fileUrl" class="urlText">
                                <file-upload 
                                @remove="fileFileRemove" 
                                :file-list.sync="fileOptions.fileList" 
                                :file-list-show.sync="fileOptions.fileListShow" 
                                :list-type="fileOptions.listType"
                                :up-file-type="fileOptions.upFileType"
                                :accept-list="fileOptions.accept"
                                @onSuccess="fileSuccessFn"
                                @getFileName="getFileName"
                                >
                                    <el-button type="default">上传附件</el-button>
                                    <div slot="tip" class="text" v-if ="showTip" >未选择任何文件</div>
                                </file-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form-item>

                

                <code class = "download">
                    <a @click="downloadExcel">下载模板</a>
                    <!-- <a href="" download="文件样式参考范本.xlsx">下载模板</a> -->
                </code>
                <div class="myrules" @mouseover="showRule = !showRule" @mouseout="showRule = false">
                    <span class="rule-title">查看模板规则</span>
                    <div class="rule-content" v-show="showRule">
                        <p>科目名称由选择的科目决定。</p>
                        <p>成绩不能为空。</p>
                        <p>单科分数的分值在0-200之间，限制小数点后1位。</p>
                        <p>学生人数在1-100之间。</p>
                    </div>
                </div>

                <div class="footer">
                    <!-- <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button> -->
                    <el-button @click='resetForm'>取消</el-button>
                    <el-button type="primary" @click="onSubmit('formInline')">发布</el-button>
                    
                </div>
            </div>
        </el-form>

    </div>
</template>

<script>
import fileUpload from 'components/Upload/fileUpload';
import { listSchoolByName, queryListClassById, listSubjectBySchoolId, listExamType, querySaveExamAndScores } from 'api/gradeManagement';
import moment from 'moment';
import TableLayout from 'components/TableLayout';
import { mapState, mapGetters } from 'vuex';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
export default {
    name: 'gradePublishPanel',
    components: { TableLayout, province, city, region, fileUpload},
    data() {
        var hasSub = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请选择课程'));
            }
            callback();
        };
        var pass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请添加附件'));
            }
            callback();
        };
        return {
            loading: true,
            showSub: false,
            showRule: false,
            showTip: true,
            downloadFile: '',
            className: '',
            examTypeName: '',
            getSchool: '',
            formInline: {// form表单数据
                schoolId: '',
                schoolName: '', // 学校名字
                typeClass: '', // 班级类型
                typeExam: '', // 考试类型
                startDate: '', // 考试开始时间
                schoolNameList: [], // 学校名字列表
                classList: [], // 班级类型列表
                examType: [], // 考试类型列表
                subjectIds: '',
                selectFiles: '',
                // subChecked: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                }
            },
            rules: {
                schoolName: [
                    {required: true, message: '请选择学校', trigger: 'change'}
                ],
                typeClass: [
                    {required: true, message: '请选择班级', trigger: 'change'}
                ],
                typeExam: [
                    { required: true, message: '请选择考试类型', trigger: 'change' }
                ],
                startDate: [
                    { type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
                ],
                subjectIds: [
                    { required: true, validator: hasSub, trigger: 'blur'}
                ],
                selectFiles: [
                    { required: true, validator: pass, trigger: 'change' }
                ]
            },
            ruleForm: {
                yearStstem: [],
                subjectList: [],
                subject: ''
            },
            // 设置上传类型
            fileOptions: {
                upFileType: 'excel',
                fileListShow: false,
                fileList: []
            },
            // 展示上传文件链接
            dataForm: {
                fileUrl: ''
            },
            dynamicTags: [], // 科目列表
            subChecked: [],
            arrList: [],
            schoolLoading: false,
            schoolLoadingSub: false,
            multipleSelection: [] // 勾选的表格的项目
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table
        }),
        ...mapGetters([
            'uid',
            'schoolId', 
            'schoolName', 
            'schoolType',
            'token'
        ])
    },
    // 初始化
    created() {
        this.getSchool = this.schoolId;
        this.formInline.schoolName = this.getSchool;
        this.queryAllClass(this.getSchool);
        this.queryClassType();
    },
    methods: {
        fileFileRemove(file) {
            this.formInline.selectFiles = '';
            this.dataForm.fileUrl = ''; 
            this.showTip = true;
        },
        fileSuccessFn(obj) {
            this.showTip = false;
            this.fileOptions.fileListShow = true;
            this.formInline.selectFiles = obj.name;
            this.dataForm.fileUrl = obj.imgUrl;
            this.$message.success('上传成功'); 
        }, 
        getFileName(obj) {
            this.formInline.selectFiles = obj.name;
        },  
        // 点击发布
        onSubmit(formInline) {
            this.findsubjectIds();
            this.$refs[formInline].validate(valid => {
                if (valid) {

                    let examTypeId = this.formInline.typeExam == ''?'' : this.formInline.typeExam, // 考试类型id
                        classId = this.formInline.typeClass == ''?'': this.formInline.typeClass, // 班级类型id
                        schoolId = this.formInline.schoolName == ''?'' : this.formInline.schoolName, // 学校id
                        startTime = this.formInline.startDate==''?'' : moment(this.formInline.startDate).format('YYYY-MM-DD'), // 时间格式处理
                        fileName = this.formInline.selectFiles,
                        url = this.dataForm.fileUrl;
                    let subjectIds = [];
                    // console.log('subChecked', this.subChecked, 'arrList', this.arrList);
                    for (var i = 0; i< this.arrList.length;i++) {
                        for (var j = 0; j< this.dynamicTags.length;j++) {
                            if (this.arrList[i]==this.dynamicTags[j].name) {
                                subjectIds.push(this.dynamicTags[j].id);
                            }
                        }
                    }
                    // console.log('---------------------------43432', schoolId, classId, examTypeId, startTime, subjectIds, fileName, url, this.subChecked);
                    
                    this.$confirm('请仔细核对，提交后将无法更改，是否要提交成绩表？', '', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' ',
                        title: ' '
                    })
                    
                    .then(() => {
                        querySaveExamAndScores(schoolId, classId, examTypeId, startTime, url, fileName, subjectIds).then(response => {
                            // console.log('response', response);
                            // if (response.status == 4006) {
                            
                            // } else if (response.status == 200) {
                            this.$store.dispatch('UpdateCache'); // 整页刷新

                            this.$message({
                                type: 'success',
                                message: '成功发布成绩'
                            });

                            this.$router.push({'name': '成绩管理'});
                            // }
                            
                        }).catch(() => {
                            // this.$confirm('发布成绩失败！请仔细阅读模板规则，请勿改动模板内容', '', {
                            //     confirmButtonText: '确定',
                            //     cancelButtonText: '取消',
                            //     type: ' ',
                            //     title: ' '
                            // });
                        });
                    }).catch(() => {
                        // this.$message({
                        //     type: 'info',
                        //     message: '发布成绩失败，下载模板后不该改动姓名和e学云ID号'
                        // });
                    });
                } else {
                    return false;
                }
            })
        },
        resetForm() {
            this.$router.go(-1);
        },
         // 学校名称模糊搜索
        remoteMethod(query) {
            if (query !== '') {
                this.schoolLoading = true;
                setTimeout(() => {
                    this.schoolLoading = false;
                    listSchoolByName(query).then(response => {
                        this.formInline.schoolNameList = response.data.content;
                    });
                }, 200);
            } else {
                this.formInline.schoolName = '';
            }
        },
        // 查询科目
        remoteMethodSub(query) {
            if (query !== '') {
                this.schoolLoadingSub = true;
                setTimeout(() => {
                    this.schoolLoadingSub = false;
                    listSubjectBySchoolId(query).then(response => {
                        if (response.data.status==200) {
                            this.showSub = true;
                            this.dynamicTags = response.data.content;
                        } else {
                            this.$message({
                                type: 'warning',
                                message: response.data.errorMsg
                            })
                        }
                    });
                }, 200);
            } else {
                // this.ruleForm.subjectList = [];
            }
        },
        // 班级列表
        queryAllClass(schoolId) {
            this.formInline.schoolId = schoolId;
            this.formInline.typeClass = '';
            queryListClassById(schoolId ? schoolId : null).then(res => {
                this.formInline.classList = res.data.content;
                this.loading = false;
            }).then(() => {
                this.remoteMethodSub(schoolId);
            });
        },
        // 考试类型
        queryClassType() {
            listExamType().then(res => {
                this.formInline.examType = res.data.content;
                this.loading = false;
            });
        },
        findMatchItem(schoolId, classId, examTypeId) {
            let obj = this.formInline.schoolNameList.find((item) => {
                return item.schoolId == schoolId;
            });
            if (obj) this.schoolName = obj.schoolName; // 学校名字

            let obj1 = this.formInline.classList.find((item) => {
                return item.pId == classId;
            });
            if (obj1) this.className = obj1.sNickName; // 班级类型名

            let obj2 = this.formInline.examType.find((item) => {
                return item.examTypeId == examTypeId;
            });
            if (obj2) this.examTypeName = obj2.examTypeName; // 考试类型名
            

        },
        findsubjectIds() {
            this.formInline.subjectIds = '';
            this.arrList = [];

            let newArr = [],
                newArr1 = [];
            for (var k = 0;k<this.dynamicTags.length;k++) {
                newArr.push(this.dynamicTags[k].name);
            }
            for (var m = 0; m<this.subChecked.length; m++) {
                newArr1[newArr.indexOf(this.subChecked[m])] = this.subChecked[m];
            }
            for (var n = 0;n<newArr1.length;n++) {
                if (newArr1[n] !== undefined) {
                    this.arrList.push(newArr1[n]);
                }
            }
            for (var i = 0; i< this.arrList.length;i++) {
                for (var j = 0; j< this.dynamicTags.length;j++) {
                    if (this.arrList[i]==this.dynamicTags[j].name) {
                        this.formInline.subjectIds += this.dynamicTags[j].id +';';
                    }
                }
            }
        },
        downloadExcel() { 
            this.loading = true; 

            this.findsubjectIds();

            let examTypeId = this.formInline.typeExam, // 考试类型id
                classId = this.formInline.typeClass, // 班级类型id
                schoolId = this.formInline.schoolName, // 学校id
                startDate = this.formInline.startDate ==''?'':Date.parse(this.formInline.startDate), // 时间格式处理
                token = this.token,
                subjectIds = this.formInline.subjectIds;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
            // console.log('classId', classId, 'subjectIds', subjectIds, 'className', this.className, 'schoolId', schoolId, 'schoolName', this.schoolName, 'examTypeName', this.examTypeName, 'examTypeId', examTypeId, 'startDate', startDate, 'token', token);
           
            if (classId ==''|| subjectIds ==''|| schoolId =='' || examTypeId =='' || startDate == '') {

                this.$confirm('请仔细核对，以上条件必须全部填写', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ',
                    title: ' '
                });
                return;
            } 

            // queryExportScoreXLS(classId, this.formInline.subjectIds, schoolId, examTypeId, token).then(response => {
            this.loading = false;          
            window.location.href = `${LOCAL_API.fyq}/score/exportTemplate?classId=${classId}&subjectIds=${subjectIds}&schoolId=${schoolId}&examTypeId=${examTypeId}&startTime=${startDate}&token=${token}`;
                    // this.$message({
                    //     type: 'success',
                    //     message: '下载成功'
                    // });
            // })
            
        }
    }
}
</script>
<style lang="scss" scoped>
@import '../../../styles/var';
code {
  font-size: 14px;
  padding: 0;
  margin-bottom: 0;
  background: transparent;
  a{
      color: #37a1fb;
  }
}
.myrules{
    display: inline-block;
    position: relative;
    font-size: 12px;
    color: #999;
    cursor: pointer;
}
.rule-content{
    z-index: 10;
    position: absolute;
    bottom: 0;
    left: 100px;
    width: 220px;
    padding: 10px;
    background: #fff;
    border: 1px solid #999;
}
.el-message-box__message {
    p {
        font-size: 18px;
        color: #333;
        text-align: center;
    }
}
.el-message-box__btns {
    text-align: center;
}
.urlText {
    // position: relative;
    // display: block;
    .text {
        // width: 155px;
        // display: inline-block;
        // overflow: hidden;
        // white-space: nowrap;
        // text-overflow: ellipsis;
        font-size: 12px;
        color: #aaa;
    }
}
.app-content {
    background:#fff;
    position: relative;
    padding: 0 50px 20px;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    .el-form{
        background:#fff;
        .appTop{
            margin-bottom:10px;
            position:relative;
        }
        .appTop p{
            margin-left:15px;
        }
        .appTop:before {
            content: '';           
            float: left;
            border-radius: 2px;
            width:4px;height:20px;
            background:#ff5e2c;
            margin-top:1px;
        }
        .addContinue{
            margin-left:60px;
            margin-top:20px
        }
        .appTitle{
            padding-top:8px;
            text-align: center;
            font-size: 18px;
            color: #333;
            line-height: 72px;
            font-weight: bold;
            font-family: Microsoft YaHei;
            border-bottom: 1px solid #ddd;
            margin-bottom: 40px;
        }
        .box{
            padding-bottom:10px;
            background:#fff;
        }
        .subjectKuang{
            // padding:0px 30px 40px 0px;
            width: 500px;
            .sub{
                margin: 0 8px;
                &:first-child{
                    margin: 0 8px 0 0;
                }
            }
        }
        .el-tag{
            margin-right:10px;
            background:#f9f9f9;
            color:#444;
        }
       
        .footer{
            text-align:center;
            margin-top: 80px;
        }
    }
    
}
</style>